package com.sim.server.service.impl;

import com.sim.core.ImConst;
import com.sim.core.ImEnvironment;
import com.sim.core.cache.redis.JedisTemplate;
import com.sim.core.packets.LoginReqBody;
import com.sim.core.packets.User;
import com.sim.core.packets.UserStatusType;
import com.sim.core.utils.*;
import com.sim.server.dto.ResponseDTO;
import com.sim.server.dto.UserInfoDTO;
import com.sim.server.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
import static com.sim.core.ImConst.CHARSET;
import static com.sim.core.ImConst.SUFFIX;

public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    /**
     * token过期时间，默认2小时(可配置)
     */
    private static final int DEFAULT_TOKEN_EXPIRE = 60 * 60 * 2;

    @Override
    public boolean logionByToken(LoginReqBody loginReqBody){
        String token = loginReqBody.getToken();
        if(StringUtils.isNotBlank(token)){
            try{
                String url = PropUtil.get("sim.auth.url");
                if(StringUtils.isBlank(url)){
                    return false;
                }
                String response = HttpClientUtil.post(url,null,token);
                ResponseDTO<UserInfoDTO> responseDTO = JsonKit.toBean(response, ResponseDTO.class);
                if(ResponseDTO.SUCCESS.equals(responseDTO.getCode())){
                    String jsonData = JsonKit.toJSONString(responseDTO.getData());
                    UserInfoDTO userInfoDTO = JsonKit.toBean(jsonData, UserInfoDTO.class);

                    //设置loginReqBody.userId
                    loginReqBody.setUserId(userInfoDTO.getUserId());

                    //缓存用户信息
                    User user = User.newBuilder()
                            .userId(userInfoDTO.getUserId())
                            .nick(userInfoDTO.getNickname())
                            .avatar(userInfoDTO.getAvatar())
                            .status(UserStatusType.ONLINE.getStatus())
                            .build();
                    this.cacheUserInfo(loginReqBody.getToken(),user);
                    return true;
                }
            }
            catch (Exception e){
                logger.error("校验token失败：{}", e.toString());
            }
        }
        return false;
    }

    @Override
    public boolean logionByPassword(LoginReqBody loginReqBody){
        if(StringUtils.isNotBlank(loginReqBody.getUserId()) && StringUtils.isNotBlank(loginReqBody.getPassword())){
            try{
                String text = loginReqBody.getUserId() + loginReqBody.getPassword();
                String key = ImConst.AUTH_KEY;
                String token = Md5.sign(text, key, CHARSET);

                //设置loginReqBody.token
                loginReqBody.setToken(token);

                //缓存用户信息
                User user = User.newBuilder()
                        .userId(loginReqBody.getUserId())
                        .nick(loginReqBody.getUserId())
                        .avatar("")
                        .status(UserStatusType.ONLINE.getStatus())
                        .build();

                this.cacheUserInfo(token,user);
                return true;
            }
            catch (Exception e){
                logger.error("校验password失败：{}", e.toString());
            }
        }
        return false;
    }

    private void cacheUserInfo(String token,User user) throws Exception {
        JedisTemplate me = JedisTemplate.me();
        String tokenExpire = PropUtil.get("sim.auth.token.expire");
        if(StringUtils.isNotBlank(tokenExpire)){
            me.set(ImConst.AUTH_KEY + SUFFIX + token,user,Integer.parseInt(tokenExpire));
        }
        else{
            me.set(ImConst.AUTH_KEY + SUFFIX + token,user,DEFAULT_TOKEN_EXPIRE);
        }
    }
}
